package com.newland.esp.controller.intercepter;

import com.alibaba.fastjson.JSONObject;
import com.newland.esp.common.util.DataResult;
import com.newland.esp.common.util.ThreadLocalUtils;
import com.newland.esp.common.util.login.TokenUtil;
import com.newland.esp.entity.user.AdminInfoEntity;
import com.newland.esp.service.user.SSOService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @param
 * @author lw
 * @descripe
 * @date 2021/8/14 19:53
 * @Version 1.0
 **/
public class ManagerLoginInterceptor implements HandlerInterceptor {

    private static Logger logger = LoggerFactory.getLogger(ManagerLoginInterceptor.class);
    @Autowired
    SSOService ssoService;


    // 请求处理的方法之前执行
    // 如果返回 true，执行下一个拦截器或目标程序，如果返回 false，不执行下一个拦截器或目标程序
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        logger.info("====拦截到了方法：{}，ManagerLoginInterceptor 在该方法执行之前执行====");


        String token = TokenUtil.getRequestToken(request);
        //1. 根据token，查询用户信息
        AdminInfoEntity adminInfoEntity = ssoService.validate(token);
        //2. 若用户不存在,
        if (adminInfoEntity == null) {
            setReturn(response,400,"请先登录哦");
            return false;
        }
        //3. token失效
//        if (adminEntity.getExpireTime().isBefore(LocalDateTime.now())) {
//            setReturn(response,400,"用户登录凭证已失效，请重新登录");
//            return false;
//        }
//        setReturn(response,200,"测试");
        ThreadLocalUtils.setMap("userTicket",token);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        logger.info("loginInfoResult: "+ThreadLocalUtils.getMap("userTicket"));
        logger.info("LEDInfoResult: "+ThreadLocalUtils.getMap("Status"));
        //移除app-user
        ThreadLocalUtils.clear();

        logger.info("loginInfoResult: "+ThreadLocalUtils.getMap("userTicket"));
        logger.info("LEDInfoResult: "+ThreadLocalUtils.getMap("Status"));

    }

    //返回错误信息
    private static void setReturn(HttpServletResponse response, int code, String msg) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        //UTF-8编码
        httpResponse.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        DataResult result = DataResult.getResult(code, msg);
        System.out.println(JSONObject.toJSONString(result));
        httpResponse.getWriter().print(JSONObject.toJSONString(result));
    }

}
